extends CharacterBody2D

@export var speed = 200.0
@export var max_health = 100
var current_health = 100

@export var experience = 0
@export var level = 1
@export var experience_needed = 10

# 武器相关 (示例，更复杂的系统会更好)
var active_weapons = []
@onready var weapon_container = $WeaponContainer

signal health_changed(new_health, max_health)
signal experience_changed(new_xp, needed_xp, current_level)
signal leveled_up(current_level)

func _ready():
	add_to_group("player")
	current_health = max_health
	emit_signal("health_changed", current_health, max_health)
	emit_signal("experience_changed", experience, experience_needed, level)
	# 初始化已有武器
	for weapon in weapon_container.get_children():
		if weapon.has_method("set_owner_player"): # 假设武器有这个方法
			weapon.set_owner_player(self)
			active_weapons.append(weapon)

func _physics_process(delta):
	# --- Movement ---
	var direction = Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down")
	velocity = direction.normalized() * speed
	move_and_slide()

	# --- Check for enemy collision (simple example) ---
	for i in get_slide_collision_count():
		var collision = get_slide_collision(i)
		if collision.get_collider().is_in_group("enemies"):
			# Simple damage taking, could be refined
			take_damage(10) # Assume enemy does 10 damage on touch


func take_damage(amount):
	current_health = max(0, current_health - amount)
	emit_signal("health_changed", current_health, max_health)
	print("Player took damage, health: ", current_health)
	if current_health <= 0:
		game_over()

func add_experience(amount):
	experience += amount
	print("Gained XP: ", amount, " | Total: ", experience, "/", experience_needed)
	while experience >= experience_needed:
		level_up()
	emit_signal("experience_changed", experience, experience_needed, level)


func level_up():
	experience -= experience_needed
	level += 1
	experience_needed = int(experience_needed * 1.5) # Increase XP needed for next level
	print("LEVEL UP! Reached Level: ", level)
	# Pause game and show upgrade screen
	get_tree().paused = true
	emit_signal("leveled_up", level) # UI listens to this


func apply_upgrade(upgrade_id):
	# --- This is where you implement the upgrade logic ---
	print("Applying upgrade: ", upgrade_id)
	match upgrade_id:
		"add_knife":
			add_new_weapon("res://scenes/weapons/basic_knife.tscn") # Example path
		"upgrade_knife_damage":
			upgrade_existing_weapon("BasicKnife", "damage", 5) # Example
		"upgrade_knife_speed":
			upgrade_existing_weapon("BasicKnife", "speed", 0.1) # Example, reduce cooldown
		"increase_health":
			max_health += 20
			current_health += 20 # Heal a bit too
			emit_signal("health_changed", current_health, max_health)
		_:
			print("Unknown upgrade selected")

	# Resume game after selection
	get_tree().paused = false


func add_new_weapon(weapon_scene_path):
	var weapon_scene = load(weapon_scene_path)
	if weapon_scene:
		var new_weapon = weapon_scene.instantiate()
		weapon_container.add_child(new_weapon)
		if new_weapon.has_method("set_owner_player"):
			new_weapon.set_owner_player(self)
		active_weapons.append(new_weapon)
		print("Added new weapon: ", new_weapon.name)


func upgrade_existing_weapon(weapon_name_or_type, stat_to_upgrade, value):
	for weapon in active_weapons:
		# You might need a better way to identify weapons (e.g., checking class name or a type variable)
		if weapon.name.contains(weapon_name_or_type): # Simple name check
			if weapon.has_method("upgrade_stat"):
				weapon.upgrade_stat(stat_to_upgrade, value)
				print("Upgraded ", weapon.name, " stat: ", stat_to_upgrade)
				# Optionally break if you only want to upgrade one instance
			else:
				print("Weapon ", weapon.name, " doesn't have upgrade_stat method")


func game_over():
	print("GAME OVER")
	# Freeze player, show game over screen, etc.
	get_tree().paused = true # Simple pause
	# You'd typically load a game over scene here or show a UI panel.


# Connect the PickupArea's area_entered signal to this function in the editor
func _on_pickup_area_area_entered(area):
	if area.is_in_group("experience_orbs"):
		add_experience(area.xp_amount)
		area.queue_free() # Remove the orb
